{% extends "base.html" %}
{% load staticfiles %}

{% block title %}我的策略{% endblock %}

{% block styles %}
    <style>

        /*表头上方的按钮样式*/
        .add-stg, .del-stg {
            width: 100px;
            height: 34px;
            margin-left: 15px;
            border-radius: 6px;
            color: white;
            border: 1px solid #ed8419;
        }

        .add-stg:hover, .del-stg:hover {
            background-color: #ed8419;
        }

        .add-stg {
            background-color: #ed6d00;
        }

        .del-stg {
            background-color: #d9534f;
        }

        /*toolbar样式*/
        .toolbar {
            margin-right: 150px;
        }

    </style>

{% endblock %}

{% block content %}

    <!--
    {#STC版本上传策略模态框#}

    {#上传策略模态框#}
    <div class="modal fade" data-backdrop="static" id="upmodal" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">上传策略</h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div style="margin-top:3%; display: block">
                            <label>策略名称</label>
                            <input class="opts" id="stgname" name="stgname" type="text"
                                   placeholder="策略名称">
                            <div id="stgname_upload_spaninfo" class="input-validation"></div>
                        </div>
                        <div style="margin-top:3%"><label>策略组</label>
                            <select class="opts" id="stggroup" name="stggroup">
                                <option name="isactive" value="1">
                                    做市策略
                                </option>
                                <option name="isactive" value="2">
                                    CTA策略
                                </option>
                                <option name="isactive" value="3">
                                    算法策略
                                </option>
                            </select>
                            <div id="stgroup_upload_spaninfo" class="input-validation"></div>
                        </div>
                        <div style="margin-top:3%"><label>策略参数</label>
                            <table style="margin-left: 40px">
                                <thead>
                                <tr class="activetable">
                                    <th>
                                        操作
                                    </th>
                                    <th>
                                        参数名*
                                    </th>
                                    <th>
                                        参数值*
                                    </th>
                                    <th>
                                        参数描述
                                    </th>
                                </tr>
                                </thead>
                                <tbody id="tb1">
                                <tr class="activetable">
                                    <td>
                                        <span style="padding:2px;cursor: pointer" class="btn-success"
                                              onclick="new_col('tb1')"><i class='fa fa-plus'></i>
                                        </span>
                                    </td>
                                    <td>
                                        <input class="activetable" name="stg_name" id="stg_name">
                                    </td>
                                    <td>
                                        <input class="activetable" name="stg_value" id="stg_value">
                                    </td>
                                    <td>
                                        <input class="activetable" name="stg_desc" id="stg_desc">
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                            <div id="paraarry_upload_spaninfo" class="input-validation"></div>
                        </div>
                        <hr/>
                        <div style="height: 20px; display: block">
                            <div style="padding-left:120px; float: left;">
                                <span class="btn-cancel btn-stc" onclick="fad_upmodeal_add_change()">取消</span>
                            </div>
                            <div style="padding-left:5px;float: left;">
                                <span class="btn-confirm btn-stc" onclick="reSub()">提交</span>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    {# 上传策略提交时弹出确认按钮 #}
    <div class="modal fade" id="modal_resub">
    </div>
    {# <!-- 上传成功模态框-->#}
    <div class="modal fade" data-backdrop="static" id="upload_success">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">上传策略</h4>
                </div>
                <div class="modal-body">
                    <div>
                        <p id="msg_upload" class="operat-success">
                            上传策略成功!</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
     -->
    {#新建策略模态框#}
    <div class="modal fade" data-backdrop="static" id="create-stg" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">新建策略</h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div style="margin-top:3%; display: block">
                            <label>策略名称</label>
                            <input class="opts" id="stgname" name="stgname" type="text"
                                   placeholder="请输入策略名称">
                            <div id="stgname_upload_spaninfo" class="input-validation"></div>
                        </div>
                        <hr/>
                        <div style="height: 20px; display: block">
                            <div style="padding-left:120px; float: left;">
                                <span class="btn-cancel btn-stc" onclick="fade_btn()">取消</span>
                            </div>
                            <div style="padding-left:5px;float: left;">
                                <span class="btn-confirm btn-stc" onclick="add_stg()">提交</span>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    {#策略删除模态框#}
    <div class="modal fade" data-backdrop="static" id="delete-stg" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">删除策略</h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div style="margin-top:3%; display: block" id="del-stg">
                            确认删除策略
                        </div>
                        <hr/>
                        <div style="height: 20px; display: block">
                            <div style="padding-left:120px; float: left;">
                                <span class="btn-cancel btn-stc" onclick="fade_btn()">取消</span>
                            </div>
                            <div style="padding-left:5px;float: left;">
                                <span id="del-commit" class="btn-confirm btn-stc" onclick="del_stg()">提交</span>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    {#申请仿真模态框#}
    <div class="modal fade" data-backdrop="static" id="paper-stg" tabindex="-1" role="dialog"
         aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">申请仿真</h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div style="margin-top:3%; display: block" id="confirm-paper">
                            确认申请仿真？
                        </div>
                        <hr/>
                        <div style="height: 20px; display: block">
                            <div style="padding-left:120px; float: left;">
                                <span class="btn-cancel btn-stc" onclick="fade_btn()">取消</span>
                            </div>
                            <div style="padding-left:5px;float: left;">
                                <span id="paper-commit" class="btn-confirm btn-stc" onclick="paper_stg()">提交</span>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Main content -->
    <body>
    <section class="content">
        <div class="nav-tabs-custom">
            <ul class="nav nav-tabs">
                <li class="active" style="margin-top:10px"><a href="#fa-pack" data-toggle="tab">我的策略</a></li>
            </ul>
            <div id="toolbar" class="toolbar">
                <button class="add-stg" onclick="add_()">新建策略</button>
            </div>
            <div class="tab-content">
                <!--我的策略头部-->
                <div class="tab-pane active" id="fa-hpquery">
                    <div style="float: left;color: red;margin-left: 174px;margin-top: -10px; display: none"
                         id="date_spaninfo"></div>
                    <table class="table-demo" id="StgTable">
                    </table>
                </div>
            </div>
        </div>
    </section>
    </body>
{% endblock %}

{% block scripts %}

    <script type="text/javascript">
        var columns = [
            {
                field: "StgID",
                title: "策略id",
                sortable: true //设置库存列可以排序
                {#visible: false#}
            }, {
                field: "StgName",
                title: "策略名",
                {#width: 100#}
            }, {
                field: "CustomerID",
                title: "创建者",
                visible: false
            }, {
                field: "CreateTime",
                title: "创建时间",
                formatter: function (data, row, index) {
                    return data.split("T").join(" ")
                }
            }, {
                field: "BackTest",
                title: "回测次数",
                {#visible: false#}
            }, {
                field: "Option",
                title: "操作",
                formatter: function (data, row, index) {
                    const del = "<span title='删除' onclick=\"del_('" + row.StgID + "')\" class='glyphicon glyphicon-trash' style='cursor: pointer'></span>&nbsp;&nbsp; ";
                    const stg_code = "&nbsp;<a title='代码策略' href='/myback/detail/?stgid=" + row.StgID + "' class='glyphicon glyphicon-pencil' style='cursor: pointer'></a>&nbsp;&nbsp; ";
                    const app_paper = "&nbsp;<span title='申请仿真' onclick=\"app_paper('" + row.StgID + "','" + row.StgName + "')\" class='glyphicon glyphicon-check' style='cursor: pointer'></span>&nbsp;&nbsp; ";
                    const detail_back = "&nbsp;<a title='历史回测' href='/myback/back_dis/?stgid=" + row.StgID + "' class='glyphicon glyphicon-new-window' style='cursor: pointer'></a>&nbsp;&nbsp; ";
                    return del + stg_code + app_paper + detail_back
                }
            }
        ]

        $(function () {
            getData()
        })

        //获取策略数据
        function getData() {
            $.ajax({
                url: '/myback/stg_serarch/',
                type: "post",
                success: function (data) {
                    if (data["type"] === 1) {
                        loadoff()
                        //初始化 bootstrap table
                        $("#StgTable").bootstrapTable("destroy").bootstrapTable({
                            {#clickToSelect:true,#}
                            columns: columns,
                            {#classes: "table table-bordered table-striped",#}
                            data: rendertable(data["stg_obj_list"]),
                            height: 500,
                            search: true,
                            toolbar: "#toolbar",
                            toolbarAlign: "right",
                            //******前端分页设置****
                            pagination: true,
                            pageNumber: 1,
                            pageSize: 20,
                            pageList: [10, 20, 50, 200],
                            paginationHAlign: "right",
                            paginationDetailHAlign: "left"
                            //******前端分页设置****
                        })
                    } else {
                        alert(data["stg_obj_list"])
                    }
                }
            })
        }

        //渲染页面
        function rendertable(data) {
            var objlist = JSON.parse(data);
            var objtable = []
            for (let i = 0; i < objlist.length; i++) {
                objlist[i].fields["StgID"] = objlist[i].pk
                objtable.push(objlist[i].fields)
            }
            return objtable
        }

        var stgid, stgname = null

        //新建模态框
        function add_() {
            $("div.modal-body > input").val("")
            $("#create-stg").modal("show")
        }

        //删除策略模态框
        function del_(stg_id) {
            stgid = stg_id
            $("#del-stg").text("确认删除策略" + stgid + "?")
            $("#delete-stg").modal("show")
        }


        //模态框取消
        function fade_btn() {
            $("#create-stg").modal("hide")
            $("#delete-stg").modal("hide")
            $("#paper-stg").modal("hide")
        }

        //新建策略
        function add_stg() {
            var stgname = $("#stgname").val()
            $.ajax({
                url: "/myback/stg_add/",
                type: "post",
                data: {
                    "stgname": stgname
                },
                success: function (data) {
                    /*
                    * data 是一个字典，包括msg和type
                    * msg 对应 具体信息
                    * type 对应信息类型，包括成功和异常
                    * */
                    if (data["type"] === 1) {
                        var stgid = data["msg"]
                        window.location.href = "/myback/detail/?stgid=" + stgid
                    } else if (data["type"] === 0) {
                        alert(data["msg"])
                    }
                }
            })
        }


        //删除策略
        function del_stg() {
            fade_btn()
            loadon()
            $.ajax({
                url: "/myback/stg_del/",
                data: {
                    "stgid": stgid
                },
                type: "post",
                success: function (data) {
                    if (data === "y") {
                        getData()
                    } else {
                        alert(data)
                    }

                }
            })
        }

        //申请仿真模态框
        function app_paper(stg_id, stg_name) {
            /**
             * 全局变量设置为点击的策略id和name
             * **/
            $("#confirm-paper").text("")
            $("#confirm-paper").text("策略" + stg_id.toString() + "确认申请仿真？")
            $("#paper-stg").modal("show");
            stgid = stg_id;
            stgname = stg_name;
        }

        //申请仿真提交
        function paper_stg() {
            /**
             * 向paper发送新增仿真策略的请求
             * **/
            fade_btn()
            loadon()

            $.post("{% url 'trade:AppPaper' %}", {"stgid": stgid, "stgname": stgname}, function (r) {
                    loadoff()
                    if (r === "y") {
                        window.location.href = "{% url 'trade:paper' %}";
                    } else if (r === "noenv") {
                        $("#msg_delete").text("缺少仿真环境，请新建后重试！")
                        $("#delete_success").modal("show");
                        setTimeout(function () {
                            $("#delete_success").modal("hide");
                        }, 2000)
                    } else {
                        console.log("后台错误：" + r.toString())
                    }
                }
            );
        }

        /*
          //上传策略取消按钮
        function fad_upmodeal_add_change() {
            $('#upmodal').modal('hide');
            $('#stgname').val('');
            $('#file').val('');
            $('#stg_name').val('');
            $('#stg_value').val('');
            $('#stg_desc').val('');
            $('#stgname_upload_spaninfo').text('');
            $('#stgfile_upload_spaninfo').text('');
            $('#paraarry_upload_spaninfo').text('');
            $('#tb1').html('')

            var tb1_html = '<tr class="activetable">\n' +
                '                                    <td>\n' +
                '                                        <span style="padding:2px;cursor: pointer" class="btn-success"\n' +
                '                                               onclick="new_col(\'tb1\')"><i class="fa fa-plus"></i>\n' +
                '                                        </span>\n' +
                '                                    </td>\n' +
                '                                    <td>\n' +
                '                                        <input class="activetable" name="stg_name" id="stg_name">\n' +
                '                                    </td>\n' +
                '                                    <td>\n' +
                '                                        <input class="activetable" name="stg_value" id="stg_value">\n' +
                '                                    </td>\n' +
                '                                    <td>\n' +
                '                                        <input class="activetable" name="stg_desc" id="stg_desc">\n' +
                '                                    </td>\n' +
                '                                </tr>'
            $('#tb1').append(tb1_html)
        }

        //上传策略模态框input框的值,
        function gets() {
            //仿真策略参数表的条数[{key,value,desc},{}]
            var pararry = []
            $("#tb1").find("tr").each(function () {
                var tdata = $(this).children()
                var paraname = tdata.eq(1).find("input").val()
                var paravalue = tdata.eq(2).find("input").val()
                var paradesc = tdata.eq(3).find("input").val()
                var paradic = {"paraname": paraname, "paravalue": paravalue, "paradesc": paradesc}
                pararry.push(paradic)
            })

            data = {
                'stgid': JSON.stringify([stgid]),
                'stgname': JSON.stringify([$('#stgname').val()]),
                'stggroup': JSON.stringify([$('#stggroup').val()]),
                // 'file': JSON.stringify([file]),
                'pararry': JSON.stringify(pararry),

            }
            return data;
        }

        //上传列表模态框显示
        function app_paper(stg_id) {
            stgid = stg_id
            $('#tb1').html('')
            var tb1_html = '<tr class="activetable">\n' +
                '                                    <td>\n' +
                '                                        <span style="padding:2px;cursor: pointer" class="btn-success"\n' +
                '                                               onclick="new_col(\'tb1\')"><i class="fa fa-plus"></i>\n' +
                '                                        </span>\n' +
                '                                    </td>\n' +
                '                                    <td>\n' +
                '                                        <input class="activetable" name="stg_name" id="stg_name">\n' +
                '                                    </td>\n' +
                '                                    <td>\n' +
                '                                        <input class="activetable" name="stg_value" id="stg_value">\n' +
                '                                    </td>\n' +
                '                                    <td>\n' +
                '                                        <input class="activetable" name="stg_desc" id="stg_desc">\n' +
                '                                    </td>\n' +
                '                                </tr>'
            $('#tb1').append(tb1_html)
            $("input").val("");
            $("select").val("");
            $("#upmodal").modal("show")
        }

        //上传策略再次确认按钮
        function reSub() {
            //每次请求再次确认页面容器是空
            $('#modal_resub').html('');
            //上传策略点击提交，错误提示信息置空
            $('#stgname_upload_spaninfo').text('');
            $("#stgroup_upload_spaninfo").text('');
            $('#stgfile_upload_spaninfo').text('');
            $('#paraarry_upload_spaninfo').text('');
            //取页面输入的值
            var data1 = gets()
            var stgname = JSON.parse(data1["stgname"])[0];
            var stggroup_value = JSON.parse(data1["stggroup"])[0];
            var stggroup = $("#stggroup").find("option[value=" + stggroup_value + "]").text().replace(/\s+/g, "");
            var pararry = JSON.parse(data1["pararry"])

            //输入框校验
            if ((stgname === '') || (stgname.length > 25)) {
                $('#stgname_upload_spaninfo').text('策略名不合法，请重新输入')
                return;
            } else if (stggroup === "") {
                $("#stgroup_upload_spaninfo").text("策略组不能为空")
                return;
            }
            for (var i in pararry) {
                if (pararry[i].paraname === '') {
                    $('#paraarry_upload_spaninfo').text('参数名不能为空')
                    return;
                } else if (pararry[i].paravalue === '') {
                    $('#paraarry_upload_spaninfo').text('参数值不能为空')
                    return;
                } else if ((pararry[i].paraname).length > 25) {
                    $('#paraarry_upload_spaninfo').text('参数名不能超过25个字符')
                    return;
                } else if ((pararry[i].paravalue).length > 25) {
                    $('#paraarry_upload_spaninfo').text('参数值不能超过25个字符')
                    return;
                } else if ((pararry[i].paradesc).length > 25) {
                    $('#paraarry_upload_spaninfo').text('参数描述不能超过25个字符')
                    return;
                }
            }


            //向再次确认页面容器添加html
            var paradiv = ""
            for (let i = 0; i < pararry.length; i++) {
                var pararow = "<tr class=\"confirm_table\">\n" +
                    "                                    <td>\n" +
                    "                                        <input class=\"confirm_table\" disabled name=\"stg_name\" value=" + pararry[i]["paraname"] + ">\n" +
                    "                                    </td>\n" +
                    "                                    <td>\n" +
                    "                                        <input class=\"confirm_table\" disabled name=\"stg_value\" value=" + pararry[i]["paravalue"] + ">\n" +
                    "                                    </td>\n" +
                    "                                    <td>\n" +
                    "                                        <input class=\"confirm_table\" disabled name=\"stg_desc\" value=" + pararry[i]["paradesc"] + ">\n" +
                    "                                    </td>\n" +
                    "                                </tr>";
                paradiv = paradiv + pararow
            }
            var confirm_strategy = '<div class="modal-dialog" style="width: 450px;">\n' +
                '            <div class="modal-content">\n' +
                '                <div class="modal-header">\n' +
                '                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>\n' +
                '                    <h4 class="modal-title">上传策略确认</h4>\n' +
                '                </div>\n' +
                '                <div class="modal-body" style="padding: 30px;height:auto">\n' +
                '                    <form>\n' +
                '                        <div style="margin-top:3%; display: block">\n' +
                '                            <label>策略名称</label>\n' +
                '                            <input disabled class="opts conf" name="stgname" type="text"\n' +
                '                                value="' + stgname + '"   >\n' +
                // '                                <span id="stgname_spaninfo" style="color: red; font-size: 14px"></span>\n' +
                '                        </div>\n' +
                '                        <div style="margin-top:3%"><label>策略组</label>\n' +
                '                            <input disabled class="opts conf" name="stggroup" type="text"\n' +
                '                                value="' + stggroup + '"   >\n' +
                // '                                <span id="stggroup_spaninfo" style="color: red; font-size: 14px"></span>\n' +
                '                        </div>\n' +
                '                        <div style="margin-top:3%"><label>策略参数</label>\n' +
                '                            <table style="background-color: white; margin:20px">\n' +
                '                                <thead>\n' +
                '                                <tr class="confirm_table">\n' +
                '                                    <th>\n' +
                '                                        参数名*\n' +
                '                                    </th>\n' +
                '                                    <th>\n' +
                '                                        参数值*\n' +
                '                                    </th>\n' +
                '                                    <th>\n' +
                '                                        参数描述\n' +
                '                                    </th>\n' +
                '                                </tr>\n' +
                '                                </thead>\n' +
                '                                <tbody>\n' + paradiv +
                '                                </tbody>\n' +
                '                            </table>\n' +
                // '                                <span id="paraarry_spaninfo" style="color: red; font-size: 14px"></span>\n' +
                '                        </div>\n' +
                '                        <hr />\n' +
                '                        <div style="height: 20px; display: block">\n' +
                '                        <div style="padding-left:120px; float: left;">\n' +
                '                            <span class="btn-cancel btn-stc" onclick="reSub_fad()">取消</span>\n' +
                '                        </div>\n' +
                '                        <div style="padding-left:5px;float: left;">\n' +
                '                                <span class="btn-confirm btn-stc" onclick="sub(gets)">提交</span>\n' +
                '                            </div>\n' +
                '                        </div>\n' +
                '                    </form>\n' +
                '                </div>\n' +
                '            </div>\n' +
                '        </div>'
            $("#modal_resub").append(confirm_strategy)
            $('#modal_resub').modal('show')

        }

        //上传策略提交逻辑
        function sub(func) {
            //此处输入框校验可不做，之前写过，懒得删了，留着无碍
            data = func();
            $('#stgname_spaninfo').text('');
            $('#paraarry_spaninfo').text('');

            for (let key in data) {
                var item = JSON.parse(data[key])[0]
                if (Boolean(item) == false && key != 'id') {
                    var title = $("#" + key).prev().text()
                    $("#" + key + "_spaninfo").text(title + '不能为空')
                    return;
                } else if (key === 'stgname') {
                    if (item.length > 25) {
                        $('#stgname_spaninfo').text('策略名称超过最大长度，请修改')
                        return;
                    }
                }
            }
            temp_para = JSON.parse(data['pararry'])

            if ((temp_para[0].paraname === '') || (temp_para[0].paravalue === '')) {
                $('#paraarry_spaninfo').text('策略参数不能为空')
                return;
            } else if (((temp_para[0].paraname).length > 25) || ((temp_para[0].paravalue).length > 25) || ((temp_para[0].paradesc).length > 25)) {
                $('#paraarry_spaninfo').text('策略参数超过最大长度，请修改')
                return;
            }


            //模态框取消
            fad_upmodeal_add_change()
            reSub_fad()
            loadon()

            {#$.post("{% url 'trade:AppPaper' %}", data, function (r) {#}
                loadoff()
                $("#delete-title").text("上传策略")
                if (r === "y") {
                    {#window.location.href = "{% url 'trade:paper' %}";#}
                } else if (r === "noenv") {
                    $("#msg_delete").text("缺少仿真环境，请新建后重试！")
                    $("#delete_success").modal("show");
                    setTimeout(function () {
                        $("#delete_success").modal("hide");
                    }, 2000)
                } else {
                    console.log("后台错误：" + r.toString())
                }
            });
        }

        //上传策略再次确认模态框的取消
        function reSub_fad() {
            $('#modal_resub').modal('hide');
            $("#modal_resub").innerHTML = "";
        }

        //新增策略参数
        function new_col(idn) {
            var h = "<tr class='activetable'>" + '<td>' +
                '                                        <span style="padding:3px; cursor: pointer" class="btn-danger small"\n' +
                '                                              onclick="$(this).parent().parent().remove()"> <i class="fa fa-minus"></i>' +
                '                                        </span>' +
                '                                    </td>' +
                "<td><input class='activetable' name='stg_name'></td>" +
                "</td>" +
                "<td><input class='activetable' name='stg_value'></td>" +
                "<td><input class='activetable' name='stg_desc'></td>" +
                "</tr>";
            $('#' + idn).append($(h));
        };
         */
    </script>

    <style>

        .table-demo {
            width: 80%;
            margin: 0 auto 0px auto;
        }

        div.pull-right > input.
    </style>

{% endblock %}